import json
import os
from Server import server, ConfigCheck, logger, var, const
from Server.Utils import network


class TerminalApp(object):
    def __init__(self):
        self.config = None

    def startApp(self):
        confPath = var.translate(const.FsConfigFilePath)
        if not os.path.exists(confPath):
            logger.error('Config File "%s" Not Found!' % confPath)
            return

        with open(confPath, 'r', encoding='utf-8') as f:
            try:
                content = f.read().replace('\\', '/')
                self.config = json.loads(var.translate(content))
                f.close()
            except json.decoder.JSONDecodeError as e:
                logger.error('Config File Format Error: ' + str(e))
                f.close()
                return

        if not ConfigCheck.check(self.config):
            return

        def onSuccess():
            if self.config['server']['proxy']['en']:
                homeUrl = ':{0}{1}'.format(self.config['server']['proxy']['http_port'],
                                           self.config['server']['proxy']['url'])
            else:
                homeUrl = ':{0}'.format(self.config['server']['port'])
            WLAN_ipv4_address = network.get_WLAN_ipv4_address()
            print('\t\tFile Server Ver', const.VERSION)
            print('----------------------------------------------------------')
            if WLAN_ipv4_address != '127.0.0.1':
                print('WLAN IPv4 Address: ', WLAN_ipv4_address)
            print('File Server Run At: [{0}:{1}]'.format(self.config['server']['ip'], self.config['server']['port']))
            print('----------------------------------------------------------')
            print('You can access in browser:')
            print('Local:   http://{0}{1}'.format('127.0.0.1', homeUrl))
            if WLAN_ipv4_address != '127.0.0.1':
                print('Network: http://{0}{1}'.format(WLAN_ipv4_address, homeUrl))
            print('----------------------------------------------------------')

        def onFail(msg):
            logger.error(msg + ' PORT: {0}'.format(self.config['server']['port']))

        server.runServer(self.config, onSuccess=onSuccess, onFail=onFail)
